package com.beetle.bauhinia.api;


import android.text.TextUtils;
import android.util.Log;

import com.beetle.bauhinia.api.body.PostDeviceToken;
import com.beetle.bauhinia.api.types.Audio;
import com.beetle.bauhinia.api.types.Image;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Date;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import rx.Observable;

/**
 * Created by tsung on 10/10/14.
 */
public class IMHttpAPI {

    private static final String TAG = IMHttpAPI.class.getSimpleName();
    private static Gson gson;

    private static IMHttp newIMHttp() {
        if (TextUtils.isEmpty(apiURL)) {
            Log.e(TAG, "please set im api url");
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(apiURL)
                .client(createOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(IMHttp.class);
    }

    static final Object monitor = new Object();
    static IMHttp singleton;

    /**
     * 创建HttpClient
     * @return
     */
    public static OkHttpClient createOkHttpClient() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (request.header("token") == null && headerToken != null) {
                    if (!TextUtils.isEmpty(headerToken)) {
                        request = request.newBuilder().addHeader("Authorization", "Basic Nzo0NDk3NjBiMTIwNjEwYWMwYjNhYmRiZDk1NTI1NGVlMA==")
                                .addHeader("token",headerToken)
                                .build();
                    }
                }
                return chain.proceed(request);
            }
        });


        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                long startTime = System.currentTimeMillis();
                Log.d(TAG,String.format("Sending request %s on %s%n%s",request.url(),chain.connection(),request.headers()));
                Response response = chain.proceed(request);
                long endTime = System.currentTimeMillis();
                Log.d(TAG,String.format(Locale.CHINA,"Received response for %s in %dms%n%s",response.request().url(),(endTime-startTime),response.headers()));

                byte[] responseBytes = response.body().bytes();
                final String responseStr = new String(responseBytes);
                Log.d(TAG,responseStr);

                return response.newBuilder().body(ResponseBody.create(MediaType.parse("application/json;charset=UTF-8"),responseBytes)).build();
            }
        });

        return builder.build();

    }

    public static IMHttp Singleton() {
        if (singleton == null) {
            synchronized (monitor) {
                if (singleton == null) {
                    singleton = newIMHttp();
                }
            }
        }

        return singleton;
    }

    private static String apiURL = "";
    private static String accessToken;
    private static String headerToken;

    public static String getHeaderToken() {
        return headerToken;
    }

    public static void setAPIURL(String url) {
        apiURL = url;
    }

    public static String getApiUrl() {
        return apiURL;
    }

    public static void setToken(String token) {
        accessToken = token;
    }

    public static void setHeaderToken(String headerToken) {
        IMHttpAPI.headerToken = headerToken;
    }

    public interface IMHttp {

        @POST("/device/bind")
        Observable<Object> bindDeviceToken(@Body PostDeviceToken token);

        @POST("/device/unbind")
        Observable<Object> unBindDeviceToken(@Body PostDeviceToken token);

        @Multipart
        @POST("/course/images")
        @Headers({"contentType:multipart/form-data"})
        Call<ResponseBody> postImages(@Part MultipartBody.Part file);

        @Multipart
        @POST("/course/audios")
        Call<ResponseBody> postAudios(@Part MultipartBody.Part file);
    };


}
